﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TabControlNew
{
    public delegate bool PreRemoveTab(int indx);

    public partial class TabControlModernized : TabControl
    {
        public TabControlModernized()
            : base()
        {
            PreRemoveTabPage = null;
            this.DrawMode = TabDrawMode.OwnerDrawFixed;
         //   this.Selecting += new TabControlCancelEventHandler(SelectingTab);
        }

        public void AddTab(string name)
        {
            TabPage tp = new TabPage(name + "   ");
            this.TabPages.Add(tp);
        }

        public PreRemoveTab PreRemoveTabPage;

        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            Rectangle z = GetTabRect(e.Index);
            z.Offset(2, 2);
            Rectangle r = GetTabRect(e.Index);
            r.Offset(2, 2);
            r.X = r.X + r.Width - 12;
            r.Y = r.Y + r.Height - 14;
            r.Width = 6;
            r.Height = 6;
            Brush b = new SolidBrush(Color.Black);
            Pen p = new Pen(b, (float)1.6);
            e.Graphics.DrawLine(p, r.X, r.Y, r.X + r.Width, r.Y + r.Height);
            e.Graphics.DrawLine(p, r.X + r.Width, r.Y, r.X, r.Y + r.Height);

            string titel = this.TabPages[e.Index].Text;
            Font f = this.Font;
            e.Graphics.DrawString(titel, f, b, new PointF(z.X, z.Y));
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            Point p = e.Location;
            for (int i = 0; i < TabCount; i++)
            {
                Rectangle r = GetTabRect(i);
                r.Offset(2, 2);
                r.X = r.X + r.Width - 12;
                r.Y = r.Y + r.Height - 14;
                r.Width = 6;
                r.Height = 6;
                if (r.Contains(p))
                {
                    CloseTab(i);
                }
            }
        }

        private void CloseTab(int i)
        {
            if (PreRemoveTabPage != null)
            {
                bool closeIt = PreRemoveTabPage(i);
                if (!closeIt)
                    return;
            }
            TabPages.Remove(TabPages[i]);
        }
    }
}
